package com.origin.app.page.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations.map
import com.google.gson.GsonBuilder
import com.luck.picture.lib.utils.SpUtils
import com.origin.app.MyApplication
import com.origin.app.bean.BaseNetBean
import com.origin.app.bean.TodayHistoryBean
import com.origin.app.bean.UserInfoBean
import com.origin.app.utils.NetAppUtils
import com.origin.app.utils.UserInfoUtils
import com.origin.baselibrary.viewmodel.BaseViewModel
import com.origin.utils.MD5Utils
import com.origin.utils.SharedPreferencesUtils
import com.origin.utils.log.LogUtils
import ikidou.reflect.TypeBuilder


class LoginViewModel : BaseViewModel() {
    val loginMutableLiveData = MutableLiveData<Boolean>()
    fun loginAction(userName: String, passWord: String) {
        val map = mapOf("user_name" to userName, "user_pwd" to MD5Utils.md5(passWord) ,"system_id" to 2)
        viewModelSuspend {
            val prettyJson = GsonBuilder().setPrettyPrinting().create().toJson(map)
            val type = TypeBuilder.newInstance(BaseNetBean::class.java).addTypeParam(UserInfoBean::class.java).build()
            LogUtils.__e("登录接口 a : ${NetAppUtils.loginUrl}")
           var netBean = NetAppUtils.privatePostJsonStr<BaseNetBean<UserInfoBean>>(NetAppUtils.loginUrl, prettyJson, type, this);
            LogUtils.__e("登录接口 b : ${NetAppUtils.loginUrl}")
            LogUtils.__e("登录接口 c : ${netBean.code}")
            if(netBean.isOk){
                UserInfoUtils.saveUserInfo(netBean.data);
                loginMutableLiveData.postValue(true)
            }
        }

    }

    fun todayOnHistory() {
        viewModelSuspend {
            val type = TypeBuilder.newInstance(TodayHistoryBean::class.java)
                .build()
            val url = "http://v.juhe.cn/todayOnhistory/queryEvent.php?date=10/1&key=826595764fa1889acb466b656a319a8b"
            val todayHistoryBean = NetAppUtils.get<TodayHistoryBean>(url,  type, this);
            if (todayHistoryBean.error_code == 0){
                if(todayHistoryBean.result.size>0){
                    val result= todayHistoryBean.result[0]
                    LogUtils.__e("todayOnHistory c : ${result.title}")
                }
            }
        }
    }
}